<?php
/**
 *
 *
 * @author Zeon <scplay@gmail.com>
 * @date 2019/5/28 14:36
 * @copyright PanxSoft Inc.
 */

namespace App\Http\Controllers\App\V1;


use App\Http\Controllers\ApiController;
use App\Http\Requests\App\V1\AppVersion\AppVersionStoreRequest;
use App\Models\AppVersion;
use App\Services\EasySms\AliSMSCountry;
use Illuminate\Http\Request;

class AppVersionController extends ApiController
{
    const ROUTES = [
        'index'      => 'app.v1.app-version.index',
        'showLatest' => 'app.v1.app-version.showLatest',
        'store'      => 'app.v1.app-version.store',
    ];

    /**
     * @deprecated - Android 说不需要列表
     * @see showLatest()
     * App 版本
     *
     * @param Request $request
     *
     * @return array|\Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $app_versions = (new AppVersion)
            ->where('platform', $request->get('platform'))
            ->latest()
            ->get();

        return $this->response(compact('app_versions'));
    }

    public function showLatest(Request $request)
    {
        $app_version = (new AppVersion)
            ->where('platform', $request->get('platform'))
            ->latest()
            ->first();

        return $this->response(compact('app_version'));
    }

    /**
     * @param AppVersionStoreRequest $request
     *
     * @return array|\Illuminate\Http\Response
     * @throws \App\Exceptions\ApiAbstractException
     */
    public function store(AppVersionStoreRequest $request)
    {
        $file_byte = $this->getUrlContentLength($request->download_url);

        $data = [
            'download_url' => $request->download_url,
            'platform'     => $request->platform,
            'version'      => $request->version,
            'description'  => $request->description,
            'force_update' => $request->force_update,
            'size'         => $file_byte,
        ];

        $app_version = (new AppVersion)->create($data);

        return $this->response(compact('app_version'));
    }

    /**
     * @param string $url
     *
     * @return mixed
     * @throws \App\Exceptions\ApiAbstractException
     */
    private function getUrlContentLength(string $url): ?int
    {
        try {
            $header_array = get_headers($url, true);

            return $header_array['Content-Length'];
        } catch (\Exception $exception) {
            $this->checkFailed("url: $url cannot access [{$exception->getMessage()}]");

            return null;
        }
    }
}